/**  
  -- The Performance Driven Lime Project -- 

  A self adaptive tuple space for mobile agents and hosts by dynamic
  adapting tuple's replication policy.
  
  Copyright (C) 2008
  Xing Jiankuan, Pan Wenhui
  SAGroup of Tsinghua University

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  Lesser General Public License for more details.

  You should have received this copy of the GNU Lesser General Public
  License along with this library; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 
 */
package lime2;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import lights.interfaces.ITuple;
import sagroup.util.Lights;

class ReactionTree {
	Map<String, ReactionTree> childs = new HashMap<String, ReactionTree>();
	Map<ReactionID, RegisteredReaction> items = new HashMap<ReactionID, RegisteredReaction>();
	Map<ReactionID, RegisteredReaction> wilditems = new HashMap<ReactionID, RegisteredReaction>();

	public String toString() {
		StringBuilder sb = new StringBuilder();
		toString(sb, 0);
		return sb.toString();
	}

	private void toString(StringBuilder sb, int i) {
		for (int j = 0; j < i; j++) {
			sb.append('\t');
		}
		sb.append("level" + i + "has ");
		sb.append("items: " + items);
		sb.append("wilditems: " + wilditems);
		sb.append('\n');
		i++;
		Set<Map.Entry<String, ReactionTree>> s = childs.entrySet();
		for (Iterator iterator = s.iterator(); iterator.hasNext();) {
			Map.Entry<String, ReactionTree> entry = (java.util.Map.Entry<String, ReactionTree>) iterator
					.next();
			entry.getValue().toString(sb, i);
		}
	}

	private ReactionTree getChild(String className) {
		ReactionTree ret = childs.get(className);

		if (ret == null) {
			ret = new ReactionTree();
			childs.put(className, ret);
		}
		return ret;
	}

	private ReactionTree onlyGetChild(String className) {
		ReactionTree ret = childs.get(className);
		return ret;
	}

	public void findMatchRecusive(ITuple newTuple, List<RegisteredReaction> ret) {
		int depth = 0;
		ReactionTree currentNode = this;
		while (currentNode != null && depth < newTuple.length()) {
			ABaseRRMgr.findMatchTemplate(currentNode.wilditems, newTuple, ret);
			if (currentNode.childs.isEmpty()) {
				/*
				 * This branch is for performance optimization, because
				 * getType() is time consuming.
				 */
				currentNode = null;
			} else {
				currentNode = currentNode.onlyGetChild(newTuple.get(depth)
						.getType().getName());
			}
			depth++;
		}
		if (currentNode != null) {
			ABaseRRMgr.findMatchTemplate(currentNode.wilditems, newTuple, ret);
			ABaseRRMgr.findMatchTemplate(currentNode.items, newTuple, ret);
		}
	}

	public void removeRecursive(ITuple template, ReactionID rids, int i) {
		if (Lights.isWildTemplate(template)) {
			ReactionTree position = getWildPosition(template, 0);
			position.wilditems.remove(rids);

		} else {
			ReactionTree position = getPosition(template, 0);
			position.items.remove(rids);
		}
	}

	/**
	 * now, if we remove a template which is not in tree and have no branch, we
	 * construct that branch. Although that may be of no need, we leave that be
	 * for easily coding without much performance and storage penalty.
	 */
	private ReactionTree getPosition(ITuple template, int i) {
		if (template.length() > (i)) {
			return getChild(template.get(i).getType().getName()).getPosition(
					template, i + 1);
		} else if (template.length() == (i)) {
			return this;
		} else {
			throw new RuntimeException("should not reach here!");
		}
	}

	private ReactionTree getWildPosition(ITuple template, int i) {
		if (template.length() > (i + 1)) {
			return getChild(template.get(i).getType().getName())
					.getWildPosition(template, i + 1);
		} else if (template.length() == (i + 1)) {
			return this;
		} else {
			throw new RuntimeException("should not reach here!");
		}
	}

	public void insertRecursive(ITuple template,
			RegisteredReaction newReaction, int i) {
		if (Lights.isWildTemplate(template)) {
			ReactionTree position = getWildPosition(template, 0);
			position.wilditems.put(newReaction.getReactionID(), newReaction);

		} else {
			ReactionTree position = getPosition(template, 0);
			position.items.put(newReaction.getReactionID(), newReaction);
		}
	}

}